﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using System.Threading.Tasks;
using WebTest.Infrastructure.Interfaces;
using WebTest.Infrastructure.NLog;
using WebTest.WebApi.Filter;

namespace WebTest.WebApi.Configuration
{
    public static class ConfigureApplication
    {
        public static IServiceCollection AddApplicationService(this IServiceCollection services, IConfiguration configuration)
        {
            // 添加全局异常拦截
            services.AddControllers(options => options.Filters.Add(typeof(GlobalExceptionFilterAsync)));

            // 注入请求上下文访问
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            // Nlog异常处理服务
            services.AddSingleton<INLogService, NLogService>();

            // JwtToken 验证配置
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
                .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                {
                    var serverSecret = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtToken:Serect"]));
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        IssuerSigningKey = serverSecret,
                        //RequireExpirationTime = true,
                        //ClockSkew = TimeSpan.Zero,
                        ValidIssuer = configuration["JwtToken:Issuer"],
                        ValidAudience = configuration["JwtToken:Audience"]
                    };
                });
                    //services.AddAuthentication(options =>
                    //   {
                    //       options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    //       options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    //   })
                    //    .AddJwtBearer(options =>
                    //    {
                    //        //options.Events = new JwtBearerEvents
                    //        //{
                    //        //    // 黑名单Token
                    //        //    OnTokenValidated = context =>
                    //        //    {
                    //        //        var token = (context.SecurityToken as JwtSecurityToken).RawData;
                    //        //        if (InBlacklist(token))
                    //        //        {
                    //        //            context.Fail("token in blacklist");
                    //        //        }
                    //        //        return Task.CompletedTask;
                    //        //    },
                    //        //    OnAuthenticationFailed = context =>
                    //        //    {
                    //        //        context.NoResult();

                    //        //        context.Response.StatusCode = 401;
                    //        //        context.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = context.Exception.Message;
                    //        //        return Task.CompletedTask;
                    //        //    }
                    //        //};


                    //        options.TokenValidationParameters = new TokenValidationParameters
                    //        {
                    //            //ValidateIssuer = true,
                    //            ValidIssuer = configuration["JwtToken:Issuer"],

                    //            //ValidateAudience = true,
                    //            ValidAudience = configuration["JwtToken:Audience"],

                    //            //ValidateIssuerSigningKey = true,
                    //            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtToken:Serect"])),

                    //            ClockSkew = TimeSpan.Zero
                    //            //ValidateLifetime = true
                    //        };
                    //    });

                    //services.AddAuthorization(options =>
                    //{
                    //    options.AddPolicy("Admin", policy => policy.RequireRole("Admin").Build());
                    //});

                    return services;
        }

        static bool InBlacklist(string token)
        {
            return false;
        }
    }
}
